<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <!-- 搜索区域 -->
      <el-row class="ml10" v-show="showSearch">
        <el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList" ref="queryRef">
          <div>
            <el-button @click="formDialogRef.openDialog()" class="ml10" icon="folder-add" type="primary">新增</el-button>
            <!-- 批量删除按钮 -->
            <el-button
                @click="deleteBatch"
                class="ml10"
                icon="delete"
                type="danger"
                :disabled="selectObjs.length === 0"
            >
              批量删除
            </el-button>
          </div>
          <el-form-item label="名称" prop="itineraryName" style="padding-top:10px">
            <el-input placeholder="行程库名称" style="max-width: 180px" v-model="state.queryForm.itineraryName" />
          </el-form-item>
          <el-form-item label="创建人" prop="createBy">
            <el-input placeholder="创建人" style="max-width: 180px" v-model="state.queryForm.createBy" />
          </el-form-item>
          <el-form-item>
            <el-button @click="getDataList" icon="search" type="primary">查询</el-button>
          </el-form-item>
        </el-form>
      </el-row>

      <el-table :data="state.dataList"
                @selection-change="handleSelectionChange"
                style="width: 100%"
                v-loading="state.loading"
                border
                :cell-style="tableStyle?.cellStyle"
                :header-cell-style="tableStyle?.headerCellStyle"
      >
        <el-table-column align="center" type="selection" width="40" />
        <el-table-column label="序号" type="index" width="60" />
        <el-table-column label="名称" prop="itineraryName" show-overflow-tooltip />
        <el-table-column label="创建人" prop="createBy" show-overflow-tooltip />
        <el-table-column label="创建时间" prop="createTime" show-overflow-tooltip />
        <el-table-column label="描述" prop="remark" show-overflow-tooltip />
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button
                icon="edit-pen"
                @click="formDialogRef.openDialog(scope.row.itineraryId, false)"
                text
                type="primary"
            >
              修改
            </el-button>
            <el-button icon="eye" @click="formDialogRef.openDialog(scope.row.itineraryId, true)" text type="primary">详情</el-button>
            <el-button icon="delete" @click="handleDelete(scope.row)" text type="danger">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <pagination
          @current-change="currentChangeHandle"
          @size-change="sizeChangeHandle"
          v-bind="state.pagination"
      />
    </div>
    <form-dialog @refresh="getDataList()" ref="formDialogRef" />
  </div>
</template>

<script lang="ts" name="trip" setup>
import { BasicTableProps, useTable } from '/@/hooks/table';
import { selectItineraryByCondition, deleteItinerary, deleteItineraryBatch } from '/@/api/itinerary/itinerary';
import { useMessage } from '/@/hooks/message';
import { defineAsyncComponent, ref, reactive } from 'vue';
import { useDict } from "/@/hooks/dict";
import { ElMessage, ElMessageBox } from 'element-plus';

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
const { trip_staus } = useDict('trip_staus');

// 定义变量
const formDialogRef = ref();
const queryRef = ref();
const showSearch = ref(true);
const selectObjs = ref([]) as any;
const multiple = ref(true);

const state: BasicTableProps & {
  dataList: any[];
  loading: boolean;
  pagination: any;
  queryForm: {
    itineraryName?: string;
    createBy?: string;
  };
} = reactive({
  queryForm: {},
  dataList: [],
  loading: false,
  pagination: {
    total: 0,
    pageSize: 10,
    currentPage: 1
  },
  pageList: selectItineraryByCondition,
});

const {
  getDataList: originalGetDataList,
  currentChangeHandle,
  sizeChangeHandle,
  tableStyle
} = useTable(state);

const getDataList = async () => {
  const hasSearchParams = Object.values(state.queryForm).some(v => v);
  if (hasSearchParams) {
    try {
      state.loading = true;
      const params = {
        page: state.pagination.currentPage,
        size: state.pagination.pageSize,
        itineraryName: state.queryForm.itineraryName || '',
        createBy: state.queryForm.createBy || '',
      };
      const res = await selectItineraryByCondition(params);
      state.dataList = res.data.records || [];
      state.pagination.total = res.data.total || 0;
    } catch (error) {
      useMessage().error('查询失败，请重试');
      console.error('查询错误:', error);
    } finally {
      state.loading = false;
    }
  } else {
    await originalGetDataList();
  }
};

const resetQuery = () => {
  state.queryForm = {};
  if (queryRef.value) {
    queryRef.value.resetFields();
  }
  getDataList();
};

const handleSelectionChange = (objs: { itineraryId: string }[]) => {
  selectObjs.value = objs.map(({ itineraryId }) => itineraryId);
  multiple.value = !objs.length;
};

const handleDelete = async (row) => {
  if (!row || !row.itineraryId) {
    ElMessage.warning('未找到有效的数据ID');
    return;
  }
  try {
    await ElMessageBox.confirm(
        `确定要删除行程单 ${row.itineraryName} 吗？此操作不可撤销。`,
        '删除确认',
        {
          confirmButtonText: '确认删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
    );
    await deleteItinerary({ itineraryId: row.itineraryId });
    getDataList();
    ElMessage.success('删除成功');
  } catch (err: any) {
    if (err !== 'cancel') {
      ElMessage.error(err.msg || '删除失败，请稍后重试');
    }
  }
};

// 批量删除逻辑
const deleteBatch = async () => {
  if (selectObjs.value.length === 0) {
    ElMessage.warning('请先选择需要删除的行程');
    return;
  }
  try {
    await ElMessageBox.confirm(
        `确定要删除选中的 ${selectObjs.value.length} 条行程吗？此操作不可撤销。`,
        '批量删除确认',
        {
          confirmButtonText: '确认删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
    );
    // 调用批量删除接口
    await deleteItineraryBatch(selectObjs.value);
    getDataList();
    ElMessage.success('批量删除成功');
    selectObjs.value = [];
  } catch (err: any) {
    if (err !== 'cancel') {
      ElMessage.error(err.msg || '批量删除失败，请稍后重试');
    }
  }
};
</script>
